import time
import os
from datetime import datetime, timedelta

"""
time模块 
时间的访问和转换，该模块都是系统级的
"""


def my_time():
    time.sleep(1.0)
    """
    查看时间
    """
    # 获取当前时间
    print(f'当前时间：{time.localtime()}')

    # 改变时区，UTC时间就是通用时间，世界统一时间，没有时区（了解）
    # os.environ['TZ'] = 'US'
    # time.tzset()

    # 时间戳  时间戳是从1970年1月1日（UTC/GMT的午夜）开始所经过的秒数，不考虑闰秒
    # 单位：秒, 精度：微秒
    print(f'当前时间戳：{time.time()}')

    """
    时间格式转换
    """
    # time.struct_time -> str
    struct_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print(f'struct_time -> str：{struct_str}')

    # str -> time.struct_time
    print(f'str -> struct_time：{time.strptime(struct_str, "%Y-%m-%d %H:%M:%S")}')

    # time.struct_time -> tuple
    tuple_time = tuple(time.localtime())
    print(f'struct_time -> tuple：{tuple_time}')

    # tuple -> time.struct_time
    print(f'tuple -> struct_time：{time.struct_time(tuple_time)}')

    # timestamp -> time.struct_time
    struct_time = time.localtime(time.time())  # 提供了有时区接口
    print(f'timestamp -> struct_time：{struct_time}')
    gm_time = time.gmtime(time.time())  # 没有时区
    print(f'timestamp -> gm_time：{gm_time}')

    # time.struct_time -> timestamp
    ts = time.mktime(struct_time)  # 时间精度会丢失
    print(f'struct_time -> timestamp：{ts}')

    # 时间运算  只能通过时间格式 -> 元组，然后创建新元组来新建一个新的时间


"""
datetime：对time模块的进一步封装，功能更强大
练习使用了datetime.datetime模块
"""


def my_datetime():
    """
    查看时间
    """
    # today()  now()  utcnow()
    # today() 返回的是 -> datetime.datetime(2020, 11, 8, 13, 44, 27, 473545)
    # 然后通过 print()调用的输出接口返回的格式是 -> 2020-11-08 13:45:43.446891
    print(datetime.today())
    print(datetime.now(tz=None))  # 可以指定时区,默认是None
    print(datetime.utcnow())  # 返回utc时间

    """
    时间格式的转换
    """
    # datetime.datetime -> str
    # 注意：此处并不像time模块一样用模块调用，而是用datetime.datetime对象来转换：[datetime.datetime].strftime("%Y-%m-%d %H:%M:%S")
    now = datetime.today()
    datetime_str = now.strftime("%Y-%m-%d %H:%M:%S")
    print(f'datetime -> str：{datetime_str}')

    # str -> datetime.datetime
    str_datetime = now.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
    print(type(str_datetime))  # <class 'datetime.datetime'>
    print(f'str -> datetime：{str_datetime}')  # str_datetime提供了__str__接口，所以此处print调用了此接口又转换成了字符串 2020-11-08 14:08:47

    # datetime.datetime -> timetuple -> tuple
    struct_time = now.timetuple()
    tuple_time = tuple(struct_time)
    print(f'datetime -> timetuple -> tuple：{tuple_time}')

    # tuple -> datetime.datetime
    new_tuple = tuple_time[:-3]
    print(f'tuple -> datetime：{datetime(*new_tuple)}')  # *是代表省略没有传输的参数

    # datetime.datetime -> timestamp
    dt = now.timestamp()
    print(f'datetime -> timestamp:{dt}')

    # timestamp -> datetime.datetime
    td = datetime.fromtimestamp(now.timestamp())
    print(type(td))
    print(f'timestamp -> datetime:{td}')

    """
    时间运算
    """
    print(f'未修改时间：{now}')
    delta_time = now + timedelta(seconds=1.0, microseconds=100.0,
                                 milliseconds=10.0, minutes=-10.0,
                                 hours=2.0, weeks=-1.0, days=-1.0)
    print(f'修改后的时间：{delta_time}')


# 封装一个函数get_date(days) , 通过传入的数值days(days=1[-2,3,4,5]), 返回格式化后的时间
def get_date(days):
    try:
        day = float(days)
    except Exception as e:
        raise ParamsTypeError('请输入数字：{}'.format(e.args))
    else:
        now = datetime.today()
        time_result = now + timedelta(days=float(day))
        return time_result
    finally:
        pass


# 自定义异常
class ParamsTypeError(Exception):
    pass


if __name__ == '__main__':
    my_time()
    print('------------------------我是分割线------------------------------')
    my_datetime()
    print('------------------------我是分割线------------------------------')
    days = input('请输入你要计算哪天的时间:')
    result = get_date(days)
    print(f'你要计算的时间结果为：{result}')
